package org.yty.travelagencyredis.Dao.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.yty.travelagencyredis.Dao.GroupMessageDao;
import org.yty.travelagencyredis.model.DTO.HistoryGroupMessageQueryDTO;
import org.yty.travelagencyredis.model.Entity.GroupMessage;

import java.time.LocalDateTime;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class GroupMessageDaoImpl implements GroupMessageDao {
    private final StringRedisTemplate redisTemplate;

    @Override
    public void insert(GroupMessage groupMessage) {
        groupMessage.setId(IdUtil.getSnowflakeNextId());
        groupMessage.setCreateTime(LocalDateTime.now());
        this.redisTemplate.opsForHash().put(GroupMessage.key, groupMessage.getId(), JSON.toJSONString(groupMessage));
    }

    @Override
    public List<GroupMessage> getHistoryMessages(HistoryGroupMessageQueryDTO historyGroupMessageQueryDTO) {
        return this.redisTemplate.opsForHash().values(GroupMessage.key)
                .stream().map(jsonString -> JSON.parseObject((String) jsonString, GroupMessage.class))
                .filter(item -> item.getChatGroupId().equals(historyGroupMessageQueryDTO.getChatGroupId()))
                .skip((historyGroupMessageQueryDTO.getPageNo() - 1) * 10)
                .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                .limit(10).toList();
    }

    @Override
    public List<GroupMessage> getMessages(Long chatGroupId) {
        return this.getHistoryMessages(new HistoryGroupMessageQueryDTO(chatGroupId,1L));
    }
}
